package com.weiiew.backend.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws")
                .setAllowedOriginPatterns("*")
                .withSockJS(); // 前端连接端点
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/topic", "/queue"); // 代理目的地前缀（订阅用）
        registry.setApplicationDestinationPrefixes("/app"); // 应用目的地前缀（消息发送用）
    }

    // 配置入站通道线程池
    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        registration.taskExecutor(inboundTaskExecutor());
    }

    // 配置出站通道线程池 (重点解决 clientOutboundChannel)
    @Override
    public void configureClientOutboundChannel(ChannelRegistration registration) {
        registration.taskExecutor(outboundTaskExecutor());
    }

    // 创建入站通道线程池 (兼容 Spring Boot 2.6)
    @Bean(name = "inboundTaskExecutor")
    public ThreadPoolTaskExecutor inboundTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(20);
        executor.setThreadNamePrefix("ws-inbound-");
        executor.setAwaitTerminationSeconds(4);  // 等待线程终止时间
        executor.setWaitForTasksToCompleteOnShutdown(true); // 关键配置
        executor.initialize();
        return executor;
    }

    // 创建出站通道线程池 (兼容 Spring Boot 2.6)
    @Bean(name = "outboundTaskExecutor")
    public ThreadPoolTaskExecutor outboundTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(20);
        executor.setThreadNamePrefix("ws-outbound-");
        executor.setAwaitTerminationSeconds(4);
        executor.setWaitForTasksToCompleteOnShutdown(true); // 关键配置
        executor.initialize();
        return executor;
    }

    // 配置任务调度器 (用于心跳等)
    @Bean(name = "websocketTaskScheduler", destroyMethod = "shutdown")
    public ThreadPoolTaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setPoolSize(5);
        scheduler.setThreadNamePrefix("ws-scheduler-");
        scheduler.setAwaitTerminationSeconds(4);
        scheduler.setWaitForTasksToCompleteOnShutdown(true);
        scheduler.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); // 重要
        return scheduler;
    }
}